/***************************************************************************//**
 * @file mscsim_main.cpp
 * @author  Marek M. Cel <marekcel@mscsim.org>
 *
 * @section LICENSE
 *
 * Copyright (C) 2013 Marek M. Cel
 *
 * This file is part of MScpSim-> You can redistribute and modify it under
 * the terms of GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Further information about the GNU General Public License can also be found
 * on the world wide web at http://www.gnu.org.
 ******************************************************************************/
#ifndef MSCSIM_MAIN_CPP
#define MSCSIM_MAIN_CPP
#endif

////////////////////////////////////////////////////////////////////////////////

#include <fstream>
#include <iostream>

#include <QApplication>
#include <QDir>

#include <mscsim_defs.h>

#include <Simulation.h>

////////////////////////////////////////////////////////////////////////////////

using namespace std;

////////////////////////////////////////////////////////////////////////////////

/** This is application main function. */
int main( int argc, char *argv[] )
{
#   ifdef _LINUX_
    setenv( "LC_NUMERIC", "en_US", 1 );
#   endif

#   ifdef MSCSIM_LOGGING
    string logFilePath = QDir::homePath().toLocal8Bit().data();

    fstream logFile( ( logFilePath + "/" + MSCSIM_LOG_FILE ).c_str(), ios_base::trunc | ios_base::out );
    
    streambuf *simStream = ( logFile.is_open() ) ? logFile.rdbuf() : 0;

    streambuf *stdCout = cout.rdbuf();
    streambuf *stdCerr = cerr.rdbuf();
    
    if ( simStream )
    {
        cout.rdbuf( simStream );
        cerr.rdbuf( simStream );
    }
#   endif

    QApplication *app = new QApplication( argc, argv );
    Simulation   *sim = new Simulation();

    app->setApplicationName    ( MSCSIM_APP_NAME   );
    app->setApplicationVersion ( MSCSIM_APP_VER    );
    app->setOrganizationDomain ( MSCSIM_ORG_DOMAIN );
    app->setOrganizationName   ( MSCSIM_ORG_NAME   );

    sim->init();

    int result = app->exec();

    delete sim; sim = 0;
    delete app; app = 0;
    
#   ifdef MSCSIM_LOGGING
    cout.rdbuf( stdCout );
    cerr.rdbuf( stdCerr );

    if ( logFile.is_open() ) logFile.close();
#   endif

    return result;
}
